#include "widget.h"
renwu::renwu(QWidget *parent) : QWidget(parent)  {

    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
    setAttribute(Qt::WA_TranslucentBackground);

    kaishijiazaizhen();


    background.load(":/images/background.png");//背景图
    if (!background.isNull()) {
        setFixedSize(background.size());
    }
    woodPost.load(":/images/wood_post.png");//木桩（我亲爱的冰冰子）
    xueliang.load(":/images/xueliang.png");//血量小蜜虫
    jinshiziPixmap.load(":/images/jinshizi.png");//猿神
    jiazaidonghuazhen(":/images/doro",6,dorozhen,doroSize);//小doro

    donghuashijian.setInterval(10);//动画之间每帧间隔
    connect(&donghuashijian, &QTimer::timeout, this, &renwu::kaishidonghua);

    direnTimer.setInterval(5000);//小飞虫出现间隔
    connect(&direnTimer, &QTimer::timeout, this, &renwu::createDiren);
    direnTimer.start();

    jinshiziTimer.setInterval(7000); // 金狮子出现间隔
    connect(&jinshiziTimer, &QTimer::timeout, this, &renwu::createJinshizi);
    jinshiziTimer.start();

    xueliangAnimationIndex = 0;
    xueliangToAnimate = 0;
    xueliangTimer.setInterval(100);//血量动画每帧间隔
    connect(&xueliangTimer, &QTimer::timeout, this, &renwu::updateXueliangAnimation);

    doroIndex=0;
    doroTimer.setInterval(100); //doro动画每帧间隔
    doroScaleFactor = 0.1;//doro缩放比例
    connect(&doroTimer, &QTimer::timeout, this, &renwu::updatedoro);
    doroTimer.start();

    woodPostHealth = 100;//木桩血量
    playerHealth = 5;//角色血量
    playerX = width() - 30;
    playerY = height() - 30;

    isFirstPressA = true;
    isFirstPressD = true;
    lastPressATime = QTime::currentTime();
    lastPressDTime = QTime::currentTime();
    isAPressed = false;
    isDPressed = false;
    isALongPressed = false;
    isDLongPressed = false;

}

renwu::~renwu() {}

void renwu::paintEvent(QPaintEvent*) {

    if (!zhenjiazaiqingkuang) return;

    QPixmap scaledBackground = background.scaled(1080, 720, Qt::KeepAspectRatio);//窗口大小
    setFixedSize(scaledBackground.size());

    QPixmap buffer(size());
    buffer.fill(Qt::transparent);
    QPainter bufferPainter(&buffer);
    bufferPainter.setRenderHint(QPainter::Antialiasing);//双缓冲抗锯齿
    bufferPainter.drawPixmap(0, 0, background);

    int bottomY = height();

    int targetWidth = 400;//木桩长
    int targetHeight = 600;//高
    QPixmap scaledWoodPost = woodPost.scaled(targetWidth, targetHeight, Qt::KeepAspectRatio);
    int woodX = 30;//木桩初始位置
    int woodY = bottomY - scaledWoodPost.height()-100;
    bufferPainter.drawPixmap(woodX, woodY, scaledWoodPost);

    bufferPainter.setPen(QPen(Qt::red));
    bufferPainter.setFont(QFont("Arial", 16));
    bufferPainter.drawText(woodX+10, woodY - 20, "冰冰子爱上我: " + QString::number(woodPostHealth));//血量文字和位置


    int enemyTargetWidth = 60; // 怪物1宽度
    int enemyTargetHeight = 80; // 怪物1高度
    for (auto& diren : direnList) {
        diren.currentFrame %= direnFrames.size();
        QPixmap direnFrame = direnFrames[diren.currentFrame];
        QPixmap scaledDirenFrame = direnFrame.scaled(enemyTargetWidth, enemyTargetHeight, Qt::KeepAspectRatio);
        bufferPainter.drawPixmap(diren.position, scaledDirenFrame);
    }


    int jinshiziTargetWidth = 80; //金狮子宽度
    int jinshiziTargetHeight = 100;//金狮子高度
    for (auto& jinshizi : jinshiziList) {
        QPixmap scaledJinshizi = jinshiziPixmap.scaled(jinshiziTargetWidth, jinshiziTargetHeight, Qt::KeepAspectRatio);
        bufferPainter.drawPixmap(jinshizi.position, scaledJinshizi);
    }

    QPixmap currentFrame;

    int yOffset = -100; // 角色初始位置（高度偏移）
    if (dangqianzhuangtai == zhuangtai::kongxian && !kongxianzhen.isEmpty()) {//动作
        dangqianzhenshu %= kongxianzhen.size();
        currentFrame = kongxianzhen[dangqianzhenshu];
    } else if (dangqianzhuangtai == zhuangtai::paodong && !benpaozhen.isEmpty()) {
        dangqianzhenshu %= benpaozhen.size();
        currentFrame = benpaozhen[dangqianzhenshu];
    } else if (dangqianzhuangtai == zhuangtai::youpaodong && !youpaodongzhen.isEmpty()) {
        dangqianzhenshu %= youpaodongzhen.size();
        currentFrame = youpaodongzhen[dangqianzhenshu];
    } else if (dangqianzhuangtai == zhuangtai::houkongfan && !houkongfanzhen.isEmpty()) {
        dangqianzhenshu %= houkongfanzhen.size();
        currentFrame = houkongfanzhen[dangqianzhenshu];
        yOffset = -300; // 跳跃高度为300像素点
    } else if (dangqianzhuangtai == zhuangtai::youkongxian && !youkongxianzhen.isEmpty()) {
        dangqianzhenshu %= youkongxianzhen.size();
        currentFrame = youkongxianzhen[dangqianzhenshu];
    } else if (dangqianzhuangtai == zhuangtai::gongji && !gongjizhen.isEmpty()) {
        dangqianzhenshu %= gongjizhen.size();
        currentFrame = gongjizhen[dangqianzhenshu];
    }
    //跳跃时高度变化
    if (!currentFrame.isNull()) {
        int x = playerX - currentFrame.width();
        int y = playerY - currentFrame.height() + yOffset;
        bufferPainter.drawPixmap(x, y, currentFrame);
    }

    // 调整血量位置到右上角
    int xueliangX = width() - (xueliang.width() * 0.4 * playerHealth + 5 * (playerHealth - 1));
    int xueliangY = 30;
    //缩放血量图
    double scaleFactor = 0.4;

    for (int i = 0; i < playerHealth; ++i)
    {
        if (i == xueliangToAnimate)
        {
            if (xueliangAnimationIndex < xueliangAnimationFrames.size())
            {
                QPixmap animFrame = xueliangAnimationFrames[xueliangAnimationIndex];
                int scaledWidth = static_cast<int>(animFrame.width() * scaleFactor);
                int scaledHeight = static_cast<int>(animFrame.height() * scaleFactor);
                QPixmap scaledAnimFrame = animFrame.scaled(scaledWidth, scaledHeight, Qt::KeepAspectRatio);
                bufferPainter.drawPixmap(xueliangX + i * (scaledAnimFrame.width() + 5), xueliangY, scaledAnimFrame);
            }
        }
        else
        {
            int scaledWidth = static_cast<int>(xueliang.width() * scaleFactor);
            int scaledHeight = static_cast<int>(xueliang.height() * scaleFactor);
            QPixmap scaledXueliang = xueliang.scaled(scaledWidth, scaledHeight, Qt::KeepAspectRatio);
            bufferPainter.drawPixmap(xueliangX + i * (scaledXueliang.width() + 5), xueliangY, scaledXueliang);
        }
    }
    if (!dorozhen.isEmpty())
    {
        QPixmap residentFrame = dorozhen[doroIndex];
        int scaledWidth = static_cast<int>(residentFrame.width() * doroScaleFactor);
        int scaledHeight = static_cast<int>(residentFrame.height() * doroScaleFactor);
        QPixmap scaledResidentFrame = residentFrame.scaled(scaledWidth, scaledHeight, Qt::KeepAspectRatio);
        //doro初始位置
        int doroX = 100;
        int doroY = 100;
        bufferPainter.drawPixmap(doroX, doroY, scaledResidentFrame);
    }

    QPainter p(this);
    p.drawPixmap(0, 0, buffer);
}

//初始化动画
void renwu::jiazaizhen() {
    kongxianzhen.clear();
    kongxianzhenchicun.clear();

    benpaozhen.clear();
    benpaozhenchicun.clear();

    youpaodongzhen.clear();
    youpaodongzhenchicun.clear();

    houkongfanzhen.clear();
    houkongfanzhenchicun.clear();

    youkongxianzhen.clear();
    youkongxianzhenchicun.clear();

    gongjizhen.clear();
    gongjizhenchicun.clear();

    direnFrames.clear();

    xueliangAnimationFrames.clear();

    jiazaidonghuazhen(":/images/kongxian", 6, kongxianzhen, kongxianzhenchicun);
    jiazaidonghuazhen(":/images/paodong", 8, benpaozhen, benpaozhenchicun);
    jiazaidonghuazhen(":/images/youpaodong", 8, youpaodongzhen, youpaodongzhenchicun);
    jiazaidonghuazhen(":/images/houkongfan", 80, houkongfanzhen, houkongfanzhenchicun);
    jiazaidonghuazhen(":/images/youkongxian", 6, youkongxianzhen, youkongxianzhenchicun);
    jiazaidonghuazhen(":/images/diren", 15, direnFrames, direnzhenchicun);
    jiazaidonghuazhen(":/images/xueliang", 6, xueliangAnimationFrames, xueliangzhenchicun);
    jiazaidonghuazhen(":/images/gongji", 20, gongjizhen, gongjizhenchicun);
    jiazaidonghuazhen(":/images/doro",6,dorozhen,doroSize);

    zhenjiazaiqingkuang = true;
}
//加载动画
void renwu::jiazaidonghuazhen(const QString &prefix, int count, QVector<QPixmap> &zhen, QVector<QSize> &sizes) {
    for (int i = 1; i <= count; ++i) {//特殊命名法
        QString path = prefix + QString::number(i) + ".png";
        QPixmap pix(path);
        if (!pix.isNull()) {
            zhen.append(pix);
            sizes.append(pix.size());
        } else {
            qDebug() << "Failed to load frame: " << path;
        }
    }
}
//开始动画
void renwu::kaishijiazaizhen() {
    jiazaizhen();
    donghuashijian.start();
}
//更新doro动画
void renwu::updatedoro() {
    if (!dorozhen.isEmpty()) {
        doroIndex = (doroIndex + 1) % dorozhen.size();
        update();
    }
}
void renwu::createDiren() {
    Diren newDiren;
    newDiren.position.setX(0);

    // 限定高度范围
    int minY = 400;
    int maxY = 600;
    int randomY = QRandomGenerator::global()->bounded(minY, maxY);
    newDiren.position.setY(randomY);

    newDiren.currentFrame = 0;
    direnList.append(newDiren);
}
void renwu::createJinshizi() {
    Jinshizi newJinshizi;
    newJinshizi.position.setX(0);

    // 限定金狮子高度范围
    int minY = 400;
    int maxY = 600;
    int randomY = QRandomGenerator::global()->bounded(minY, maxY);
    newJinshizi.position.setY(randomY);

    jinshiziList.append(newJinshizi);
}
void renwu::updateXueliangAnimation() {
    if (xueliangAnimationIndex < xueliangAnimationFrames.size() - 1) {
        xueliangAnimationIndex++;
        update();
    } else {
        xueliangTimer.stop();
        if(playerHealth>0){
            playerHealth--;
        }
        xueliangToAnimate = -1;
        update();
    }
}



void renwu::huidaokongxian() {//返回空闲状态
    if (dangqianzhuangtai == zhuangtai::houkongfan || dangqianzhuangtai == zhuangtai::gongji) {
        dangqianzhuangtai = zhuangtai::kongxian;
        dangqianzhenshu = 0;
        backflipYOffset = 0;
        update();
    }
}
//键盘链接（按下）
void renwu::keyPressEvent(QKeyEvent *event) {
    if (event->key() == Qt::Key_A) {//A向左走
        if (!isAPressed) {
            dangqianzhuangtai = zhuangtai::paodong;
            if (isFirstPressA || lastPressATime.msecsTo(QTime::currentTime()) >= 50) {
                dangqianzhenshu = 0;
                isFirstPressA = false;
            }
            lastPressATime = QTime::currentTime();
            isAPressed = true;
            if (!donghuashijian.isActive()) {
                donghuashijian.start();
            }
            update();
        }
        if (event->isAutoRepeat()) {
            return;
        }
    }
    else if (event->key() == Qt::Key_D) {//D向右走
        if (!isDPressed) {
            dangqianzhuangtai = zhuangtai::youpaodong;
            if (isFirstPressD || lastPressDTime.msecsTo(QTime::currentTime()) >= 50) {
                dangqianzhenshu = 0;
                isFirstPressD = false;
            }
            lastPressDTime = QTime::currentTime();
            isDPressed = true;
            isDLongPressed = false;
            QTimer::singleShot(50, this, [this]() {
                if (isDPressed) {
                    isDLongPressed = true;

                }
            });
            if (!donghuashijian.isActive()) {
                donghuashijian.start();
            }
            update();
        }
    }
    else if (event->key() == Qt::Key_K) {//K跳跃
        dangqianzhuangtai = zhuangtai::houkongfan;
        dangqianzhenshu = 0;
        int bottomY = height();
        QPixmap currentFrame = houkongfanzhen[0];
        //跳跃后回到原位
        backflipStartY = bottomY - currentFrame.height();
        backflipYOffset = 0;

        update();
    }
    else if (event->key() == Qt::Key_J) {//J攻击
        dangqianzhuangtai = zhuangtai::gongji;
        dangqianzhenshu = 0;

        update();
    }
}
//键盘链接（松开）
void renwu::keyReleaseEvent(QKeyEvent *event) {
    if (event->key() == Qt::Key_A) {//A松开就停
        dangqianzhuangtai = zhuangtai::kongxian;
        isFirstPressA = true;
        isAPressed = false;

        dangqianzhenshu = 0;
        update();
    } else if (event->key() == Qt::Key_D) {//D松开就停
        dangqianzhuangtai = zhuangtai::youkongxian;
        isFirstPressD = true;
        isDPressed = false;
        dangqianzhenshu = 0;
        update();
    }
    update();
}
//鼠标拖拽窗口
void renwu::mousePressEvent(QMouseEvent *event) {
    if (event->button() == Qt::LeftButton) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
        tuozhuaiweizhi = event->globalPosition().toPoint() - frameGeometry().topLeft();
#else
        tuozhuaiweizhi = event->globalPos() - frameGeometry().topLeft();
#endif
    }
}

void renwu::mouseMoveEvent(QMouseEvent *event) {
    if (event->buttons() & Qt::LeftButton) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
        QPoint newPos = event->globalPosition().toPoint() - tuozhuaiweizhi;
#else
        QPoint newPos = event->globalPos() - tuozhuaiweizhi;
#endif
        xiandingweizhi(newPos);
        move(newPos);
    }
}
//动画具体处理
void renwu::kaishidonghua() {
    if (!zhenjiazaiqingkuang) return;
    if (dangqianzhuangtai==zhuangtai::paodong) {
        if (isAPressed) {
            dangqianzhenshu = (dangqianzhenshu + 1) % benpaozhen.size();
            playerX -= 10;
        }
    }
    else if (dangqianzhuangtai == zhuangtai::youpaodong) {
        if (isDPressed) {
            dangqianzhenshu = (dangqianzhenshu + 1) % youpaodongzhen.size();
            playerX += 10;
        }
    }
    else if (dangqianzhuangtai == zhuangtai::houkongfan) {
        if (dangqianzhenshu < houkongfanzhen.size() - 1) {
            dangqianzhenshu++;
            backflipYOffset = -300 * (static_cast<double>(dangqianzhenshu) / (houkongfanzhen.size() - 1));
        }
        else{ huidaokongxian();}
    }
    else if (dangqianzhuangtai == zhuangtai::gongji) {
        if (!gongjizhen.isEmpty()) {
            dangqianzhenshu = (dangqianzhenshu + 1) % gongjizhen.size();
            if (dangqianzhenshu < gongjizhen.size() - 1) {
                dangqianzhenshu++;
            } else {
                huidaokongxian();
            }
        }
    }
    else
    {
        dangqianzhenshu = (dangqianzhenshu + 1) % kongxianzhen.size();
    }

    // 怪物1动画更新
    for (auto& diren : direnList)
    {
        diren.position.setX(diren.position.x() + 6);//怪物1速度
        diren.currentFrame = (diren.currentFrame + 1) % direnFrames.size();
    }
    // 怪物2（金狮子）动画更新
    for (auto& jinshizi : jinshiziList)
    {
        jinshizi.position.setX(jinshizi.position.x() + 1); // 金狮子速度
    }
    playerX = qBound(0, playerX, width() - 30);
    playerY = qBound(0, playerY, height() - 30);
    handleCollision();
    update();
}

//限定位置（更新位置）
void renwu::xiandingweizhi(const QPoint &pos)
{
    QScreen *screen = QApplication::primaryScreen();
    QRect availableRect = screen->availableGeometry();
    int newX = qBound(availableRect.left(), pos.x(), availableRect.right() - width());
    int newY = qBound(availableRect.top(), pos.y(), availableRect.bottom() - height());
    move(newX, newY);
}


bool renwu::checkCollision(const QPoint &enemyPos, const QPixmap &enemyPixmap, const QPoint &playerPos, const QPixmap &playerPixmap, double enemyScale, double playerScale) {
    // 计算缩放后的图像大小
    QPixmap scaledEnemy = enemyPixmap.scaled(enemyPixmap.size() * enemyScale, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QPixmap scaledPlayer = playerPixmap.scaled(playerPixmap.size() * playerScale, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    QRect enemyRect(enemyPos, scaledEnemy.size());
    QRect playerRect(playerPos, scaledPlayer.size());
    QRect overlapRect = enemyRect.intersected(playerRect);//交集

    if (overlapRect.isEmpty()) {
        return false;
    }
    qDebug() << "Enemy Rect:" << enemyRect;
    qDebug() << "Player Rect:" << playerRect;
    qDebug() << "Overlap Rect:" << overlapRect;
    QImage enemyImage = scaledEnemy.toImage().convertToFormat(QImage::Format_ARGB32);
    QImage playerImage = scaledPlayer.toImage().convertToFormat(QImage::Format_ARGB32);

    int overlapPixelCount = 0; // 统计重叠非透明像素点数量（像素点碰撞）

    for (int y = 0; y < overlapRect.height(); ++y) {
        for (int x = 0; x < overlapRect.width(); ++x) {
            int enemyX = overlapRect.x() - enemyRect.x() + x;
            int enemyY = overlapRect.y() - enemyRect.y() + y;
            int playerX = overlapRect.x() - playerRect.x() + x;
            int playerY = overlapRect.y() - playerRect.y() + y;

            if (enemyX >= 0 && enemyX < enemyImage.width() && enemyY >= 0 && enemyY < enemyImage.height() &&
                playerX >= 0 && playerX < playerImage.width() && playerY >= 0 && playerY < playerImage.height()) {
                QColor enemyPixel = QColor(enemyImage.pixel(enemyX, enemyY));
                QColor playerPixel = QColor(playerImage.pixel(playerX, playerY));

                if (enemyPixel.alpha() > 0 && playerPixel.alpha() > 0) {
                    overlapPixelCount++; // 统计重叠非透明像素点
                    if (overlapPixelCount > 10) { //重叠几个像素点算成功
                        return true;
                    }
                }
            }
        }
    }

    return false;
}


void renwu::handleCollision() {
    QPixmap currentPlayerFrame;
    int yOffset = 0;
    if (dangqianzhuangtai == zhuangtai::kongxian && !kongxianzhen.isEmpty()) {
        currentPlayerFrame = kongxianzhen[dangqianzhenshu];
    }
    else if (dangqianzhuangtai == zhuangtai::paodong && !benpaozhen.isEmpty()) {
        currentPlayerFrame = benpaozhen[dangqianzhenshu];
    }
    else if (dangqianzhuangtai == zhuangtai::youpaodong && !youpaodongzhen.isEmpty()) {
        currentPlayerFrame = youpaodongzhen[dangqianzhenshu];
    }
    else if (dangqianzhuangtai == zhuangtai::houkongfan && !houkongfanzhen.isEmpty()) {
        currentPlayerFrame = houkongfanzhen[dangqianzhenshu];
        yOffset = -300;
    }
    else if (dangqianzhuangtai == zhuangtai::gongji && !gongjizhen.isEmpty()) {
        currentPlayerFrame = gongjizhen[dangqianzhenshu];
    }
    else if (dangqianzhuangtai == zhuangtai::youkongxian && !youkongxianzhen.isEmpty()) {
        currentPlayerFrame = youkongxianzhen[dangqianzhenshu];
    }

    int x = width() - currentPlayerFrame.width() - 30;
    int y = height() - currentPlayerFrame.height() + yOffset;
    QPoint playerPos(x, y);

    double playerScale = 1.0; //与缩放比例一致
    double enemyTargetWidth = 60;
    double enemyTargetHeight = 80;

  //与怪物一碰撞
    for (auto it = direnList.begin(); it != direnList.end(); ) {
        QPixmap direnFrame = direnFrames[it->currentFrame];
        double enemyScaleX = enemyTargetWidth / direnFrame.width();
        double enemyScaleY = enemyTargetHeight / direnFrame.height();
        double enemyScale = qMin(enemyScaleX, enemyScaleY);

        if (checkCollision(it->position, direnFrame, playerPos, currentPlayerFrame, enemyScale, playerScale)) {
            if (dangqianzhuangtai == zhuangtai::gongji) {
                //攻击到怪物1，怪物1直接消失
                woodPostHealth = qMax(0, woodPostHealth - 10); // 木桩扣血
                it = direnList.erase(it);
            } else {
                if (playerHealth > 0) {

                    xueliangToAnimate =  playerHealth -1; // 从最左边开始掉血
                    xueliangAnimationIndex = 0;
                    xueliangTimer.start();

                }

                if (playerHealth == 0) {

                    donghuashijian.stop();
                    jinshiziTimer.stop();
                    direnTimer.stop();
                    update();
                }
                it = direnList.erase(it);
            }
        } else {
            ++it;
        }
    }

    update();
}

